// src/App.js
import React, { useState, useEffect, useRef } from "react";
import "./App.css";

function App() {
  // 状态管理
  const [dailySalary, setDailySalary] = useState(500);
  const [startTime, setStartTime] = useState("09:00");
  const [endTime, setEndTime] = useState("18:00");
  const [timeLeft, setTimeLeft] = useState("00:00:00");
  const [earnedToday, setEarnedToday] = useState(0.0);
  const [isLocked, setIsLocked] = useState(false);
  const [showSettings, setShowSettings] = useState(false);

  const appRef = useRef(null);
  const dragOffset = useRef({ x: 0, y: 0 });

  // 计算时间差和收入
  useEffect(() => {
    const calculateTimeAndMoney = () => {
      const now = new Date();
      const today = now.toISOString().split("T")[0];

      // 解析时间
      const [startHour, startMinute] = startTime.split(":").map(Number);
      const [endHour, endMinute] = endTime.split(":").map(Number);

      // 创建日期对象
      const startDate = new Date(`${today}T${startTime}:00`);
      const endDate = new Date(`${today}T${endTime}:00`);

      // 如果当前时间早于上班时间
      if (now < startDate) {
        setTimeLeft(formatTime(endDate - startDate));
        setEarnedToday(0.0);
        return;
      }

      // 如果当前时间晚于下班时间
      if (now > endDate) {
        setTimeLeft("00:00:00");
        setEarnedToday(dailySalary);
        return;
      }

      // 计算剩余时间
      const remainingTime = endDate - now;
      setTimeLeft(formatTime(remainingTime));

      // 计算今日收入
      const totalWorkTime = endDate - startDate;
      const workedTime = now - startDate;
      const earned = (workedTime / totalWorkTime) * dailySalary;
      setEarnedToday(parseFloat(earned.toFixed(2)));
    };

    calculateTimeAndMoney();
    const timer = setInterval(calculateTimeAndMoney, 1000);

    return () => clearInterval(timer);
  }, [dailySalary, startTime, endTime]);

  // 格式化时间
  const formatTime = (ms) => {
    if (ms <= 0) return "00:00:00";

    const totalSeconds = Math.floor(ms / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    return `${hours.toString().padStart(2, "0")}:${minutes
      .toString()
      .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
  };

  // 拖拽处理函数
  const startDrag = (e) => {
    if (isLocked) return;

    const rect = appRef.current.getBoundingClientRect();
    dragOffset.current = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    };

    document.addEventListener("mousemove", onDrag);
    document.addEventListener("mouseup", stopDrag);
  };

  const onDrag = (e) => {
    if (!appRef.current) return;

    const x = e.clientX - dragOffset.current.x;
    const y = e.clientY - dragOffset.current.y;

    appRef.current.style.left = `${x}px`;
    appRef.current.style.top = `${y}px`;
  };

  const stopDrag = () => {
    document.removeEventListener("mousemove", onDrag);
    document.removeEventListener("mouseup", stopDrag);
  };

  // 提交设置
  const handleSubmit = (e) => {
    e.preventDefault();
    setShowSettings(false);
  };

  // 解析时间字符串为显示格式
  const parseTimeForDisplay = (timeStr) => {
    const [hours, minutes] = timeStr.split(":");
    return `${hours}:${minutes}`;
  };

  // 计算本月到现在为止的累计收入（工作日，今天只加到当前时刻）
  function getMonthEarnedUntilNow() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const today = now.getDate();
    let total = 0;
    for (let d = 1; d <= today; d++) {
      const day = new Date(year, month, d);
      const weekDay = day.getDay();
      if (weekDay === 0 || weekDay === 6) continue; // 跳过周末
      if (d < today) {
        total += dailySalary;
      } else if (d === today) {
        total += earnedToday;
      }
    }
    return total;
  }
  const earnedThisMonth = getMonthEarnedUntilNow();

  // useEffect(() => {
  //   if (window.require) {
  //     const { ipcRenderer } = window.require("electron");
  //     if (showSettings) {
  //       ipcRenderer.send("resize-window", { width: 300, height: 420 });
  //     } else {
  //       ipcRenderer.send("resize-window", { width: 300, height: 200 });
  //     }
  //   }
  // }, [showSettings]);

  useEffect(() => {
    if (window.require && appRef.current) {
      const { ipcRenderer } = window.require("electron");
      // 获取内容实际高度
      const rect = appRef.current.getBoundingClientRect();
      console.log(rect);
      ipcRenderer.send("resize-window", {
        width: Math.ceil(rect.width),
        height: Math.ceil(rect.height),
      });
    }
  }, [showSettings, dailySalary, startTime, endTime]);

  return (
    <div className={`app-drag-container${!isLocked ? " drag" : ""}`}>
      <div className="content no-drag">
        <div
          ref={appRef}
          className={`app-container ${isLocked ? "locked" : ""} ${
            showSettings ? "show-settings" : ""
          }`}
          onMouseDown={startDrag}
        >
          <div className={`header${isLocked ? "" : " drag"}`}>
            <div className="title">下班倒计时</div>
            <div className="controls">
              <button
                className="icon-btn no-drag"
                onClick={() => setShowSettings(!showSettings)}
              >
                ⚙️
              </button>
              <button
                className="icon-btn no-drag"
                onClick={() => setIsLocked(!isLocked)}
              >
                {isLocked ? "🔒" : "🔓"}
              </button>
              <button
                className="icon-btn close-btn no-drag"
                onClick={() => window.close()}
              >
                ✕
              </button>
            </div>
          </div>

          <div className="main-display">
            <div className="time-display">{timeLeft}</div>
            <div className="money-display">
              ¥{earnedToday.toFixed(2) || "0.00"}
            </div>
            <div className="money-display month-earned">
              这月赚了¥{earnedThisMonth.toFixed(2) || "0.00"}
            </div>
            <div className="progress-container">
              <div
                className="progress-bar"
                style={{ width: `${(earnedToday / dailySalary) * 100}%` }}
              ></div>
            </div>
          </div>

          {showSettings && (
            <div className="settings-panel">
              <h3>设置</h3>
              <form onSubmit={handleSubmit}>
                <div className="form-group">
                  <label className="no-drag">日薪 (¥)</label>
                  <input
                    className="no-drag"
                    type="number"
                    value={dailySalary}
                    onChange={(e) => setDailySalary(Number(e.target.value))}
                    min="0"
                    step="50"
                  />
                </div>

                <div className="form-group ">
                  <label className="no-drag">上班时间</label>
                  <input
                    className="no-drag"
                    type="time"
                    value={startTime}
                    onChange={(e) => setStartTime(e.target.value)}
                  />
                </div>

                <div className="form-group">
                  <label className="no-drag">下班时间</label>
                  <input
                    className="no-drag"
                    type="time"
                    value={endTime}
                    onChange={(e) => setEndTime(e.target.value)}
                  />
                </div>

                <div className="form-actions">
                  <button type="submit" className="no-drag">
                    保存
                  </button>
                  <button
                    type="button"
                    onClick={() => setShowSettings(false)}
                    className="no-drag"
                  >
                    取消
                  </button>
                </div>
              </form>
            </div>
          )}

          <div className="work-time-display">
            {parseTimeForDisplay(startTime)} - {parseTimeForDisplay(endTime)}
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;
